﻿using UnityEngine;
using System.Collections;
using System;
using UnityEngine.SceneManagement;

public class viewSwitch : MonoBehaviour {
    public Transform target;
    public Texture xueTexture;
    public AudioSource ASdie;

    public float distance = 5.0f;   //一开始的摄像机距离
    float x;    //游戏对象的x欧拉角
    float y;    //游戏对象的y欧拉角

    public bool isDead = false;

    float zDistance;    //游戏对象和相机的距离，等于-distance

    float ThreexMinLimit = 5.0f;     //第三人称Y轴最大方向角
    float ThreexMaxLimit = 80.0f;    //第三人称Y轴最小方向角
    float FirstxMinLimit = -80.0f;     //第一人称Y轴最大方向角
    float FirstxMaxLimit = 80.0f;    //第一人称Y轴最小方向角


    float xSpeed = 250.0f;  //左右移动速度
    float ySpeed = 120.0f;  //上下移动速度

    float zMinLimit = -20.0f;   //摄像机最远距离
    float zMaxLimit = -5.0f;

    float moveSpeed = 5.0f; //移速
    float jumpPower = 3.0f;    //跳跃力量

    bool isFirstPerson = false; //控制第一人称和第三人称
    float zTemp = 0.0f; //人称切换时记录第三人称z的值

    void Start()
    {
        isFirstPerson = false;  //设置第三人称开始游戏

        Vector3 angles = transform.eulerAngles;
        x = angles.x;   //获取欧拉角
        y = angles.y;
        zDistance = -this.distance; //获取距离
        //Debug.Log(this.distance);
        zTemp = zDistance;  //记录开始时z值

        if (this.GetComponent<Rigidbody>())
            this.GetComponent<Rigidbody>().freezeRotation = true;
        
    }
    

    void LateUpdate()
    {
        if (Input.GetKey(KeyCode.H))    //第一人称切换第三人称
        {
            isFirstPerson = false; //切换第三人称
            
            unlockCursor();
        }
        if (Input.GetKey(KeyCode.U))    //第三人称切换第一人称
        {
            isFirstPerson = true; //切换第一人称
            zTemp = zDistance == 0 ? zTemp : zDistance;  //第三人称切第一人称时记录z值
            lockCursor();
        }
        
        if (isFirstPerson)  //第一人称视角操作
        {
            //z = 0;
            PersonControl(1);
        }
        else  //第三人称视角操作
        {
            
            PersonControl(3);
        }

        if (target.position.y < -60)
        {
            isDead = true;
        }
    }
    
    void OnGUI()
    {
        GUIStyle style = new GUIStyle();
        style.fontSize = 100;
        style.alignment = TextAnchor.UpperCenter;
        style.normal.textColor = new Color(255, 0, 0);

        //Debug.Log("i`m in ... " + enemyNum);
        if (deadEnemyNum == enemyTotalNum)
        {
            GUI.Label(new Rect(250, 50, 200, 200), "You Win!",style);
            unlockCursor();
            Invoke("reLoad",8); //延时函数
        }

        if (isDead)
        {
            GUI.Label(new Rect(250, 50, 200, 200), "You Lose!", style);
            unlockCursor();
            Invoke("gameOver", 8); //延时函数

        }
    }

    void reLoad()
    {
        Debug.Log("i`m in ... restart");
        SceneManager.LoadScene(0);
    }

    void gameOver()
    {
        SceneManager.LoadScene(2);
    }


    public float shootFrequency = 0.3f;    //射击频率
    private float shootTime;    //记录射击时的时间
    private int deadEnemyNum = 0;   //消灭的敌人数量
    public int enemyTotalNum = 5;   //敌人总数
    private void PersonControl(int PersonMode)
    {
        MoveAndJump();
        if (Input.GetMouseButton(0))
        {
            if ((Time.time - shootTime) > shootFrequency)
            {

                //从摄像机发射一条射线到鼠标位置
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                //游戏音效
                target.GetComponent<AudioSource>().Play();
                //AudioSource.PlayClipAtPoint(target.GetComponent<AudioClip>(), target.position);
                RaycastHit hitInfo;    //射线碰撞信息
                if (Physics.Raycast(ray, out hitInfo))    //发射射线，当发生碰撞时，将信息存储到hitInfo中。
                {
                    if (hitInfo.transform.gameObject.layer == 8)
                    {
                        int hitForce = 5;
                        //Debug.Log(hitInfo.transform.gameObject.layer);
                        //hitInfo.collider.gameObject.AddComponent<Rigidbody>(); 
                        if (hitInfo.collider.gameObject.GetComponent<AudioSource>())
                        {
                            hitInfo.collider.gameObject.GetComponent<AudioSource>().Play();

                            //hitInfo.collider.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.forward, ForceMode.VelocityChange);
                            hitInfo.collider.gameObject.GetComponent<Rigidbody>().AddRelativeForce(hitInfo.point * hitForce * Time.deltaTime, ForceMode.VelocityChange);
                            //Debug.Log(hitInfo.point.x + "..." + hitInfo.point.y + "..." + hitInfo.point.z);


                            if (hitInfo.collider.gameObject.GetComponent<enemyAI>().isDead == false)
                            {
                                hitInfo.collider.gameObject.GetComponent<enemyAI>().isDead = true;
                                deadEnemyNum++;
                            }




                        }
                        else if (hitInfo.collider.gameObject.GetComponentInParent<AudioSource>())
                        {
                            hitInfo.collider.gameObject.GetComponentInParent<AudioSource>().Play();

                            //hitInfo.collider.gameObject.GetComponentInParent<Rigidbody>().AddForce(Vector3.forward, ForceMode.VelocityChange);
                            hitInfo.collider.gameObject.GetComponentInParent<Rigidbody>().AddRelativeForce(hitInfo.point * hitForce * Time.deltaTime, ForceMode.VelocityChange);


                            if (hitInfo.collider.gameObject.GetComponentInParent<enemyAI>().isDead == false)
                            {
                                hitInfo.collider.gameObject.GetComponentInParent<enemyAI>().isDead = true;
                                deadEnemyNum++;
                            }


                        }
                        else
                        {
                            //hitInfo.collider.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.forward, ForceMode.VelocityChange);
                            hitInfo.collider.gameObject.GetComponent<Rigidbody>().AddRelativeForce(hitInfo.point * hitForce * Time.deltaTime, ForceMode.VelocityChange);

                        }


                        hitInfo.collider.gameObject.GetComponent<Renderer>().material.mainTexture = xueTexture;

                        //Debug.Log(enemyNum);



                    }
                    else
                    {

                    }

                }

                shootTime = Time.time;
            }
            else
            {

            }

            
        }
        



        if (PersonMode == 3)
        {
            zDistance = zTemp;
            float temp = Input.GetAxis("Mouse ScrollWheel");
            if (this.target && (temp != 0.0f || Input.GetMouseButton(1)))
            {

                y += Input.GetAxis("Mouse X") * xSpeed * 0.02f; //左右
                x -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; //上下
                zDistance += temp * 100.0f * 0.02f;
                x = ClampAngle(x, ThreexMinLimit, ThreexMaxLimit); //鼠标上下移动的时候其实是沿X轴旋转，鼠标左右移动的时候其实是为了沿着Y轴旋转
                zDistance = Mathf.Clamp(zDistance, zMinLimit, zMaxLimit);
                zTemp = zDistance;
            }
            else
            {

            }
        }
        else
        {
            zDistance = 0;
            y += Input.GetAxis("Mouse X") * xSpeed * 0.02f; //左右
            x -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; //上下
            x = ClampAngle(x, FirstxMinLimit, FirstxMaxLimit); //鼠标上下移动的时候其实是沿X轴旋转，鼠标左右移动的时候其实是为了沿着Y轴旋转
        }
        
        this.goRight(); //一直保证摄像机移动跟随
    }


    private void shoot()
    {
        
    }
    private void MoveAndJump()
    {
        //移动和跳跃
        if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) || Input.GetKey(KeyCode.Space))
        {
            Vector3 moveVector = new Vector3(0, 0, 0); //运动方向基向量
            if (Input.GetKey(KeyCode.W))
            {
                moveVector += Vector3.forward;
            }
            if (Input.GetKey(KeyCode.S))
            {
                moveVector += Vector3.back;
            }
            if (Input.GetKey(KeyCode.A))
            {
                moveVector += Vector3.left;
            }
            if (Input.GetKey(KeyCode.D))
            {
                moveVector += Vector3.right;
            }

            //只移动，没有跳跃
            if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) && !Input.GetKey(KeyCode.Space))
            {
                //Debug.Log("111111");
                target.transform.Translate(moveVector * moveSpeed * Time.deltaTime, Space.Self);    //移动
            }
            //跳跃，可以边跳跃边移动
            else
            {
                //Debug.Log("121212");
                Vector3 jumpVector = new Vector3(0, 0, 0);  //跳跃运动方向向量
                jumpVector = Vector3.up + moveVector;
                //if (target.GetComponent<Rigidbody>().velocity.y <= 0.01)//限制跳跃次数
                //{
                //    Debug.Log(target.GetComponent<Rigidbody>().velocity.y);
                target.GetComponent<Rigidbody>().velocity = jumpVector * jumpPower;
                //}
                //else
                //{

                //}
            }
        }
        else
        {
            //没按键不动
        }
    }

    /// <summary>
    /// 锁定和隐藏光标
    /// </summary>
    private void lockCursor()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    /// <summary>
    /// 解锁并显示光标
    /// </summary>
    private void unlockCursor()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

    /// <summary>
    /// 限制angle的值在min和max之间
    /// </summary>
    /// <param name="angle"></param>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    private float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);   
    }

    /// <summary>
    /// 保持摄像机移动跟随
    /// </summary>
    private void goRight()
    {
        Quaternion rotation = Quaternion.Euler(x, y, 0);    //获取xy轴的欧拉角，人物不会左右倾斜，所以z轴欧拉角为0
        
         //加上最后一个target.position只是为了参照目标的坐标系因为去掉的话就是基于（0,0,0）
        Vector3 position = rotation * new Vector3(0.0f, 0.0f, zDistance) + target.position;

        if (zDistance == 0)
        {
            this.transform.position = new Vector3(position.x, position.y + 1.5f, position.z);  //头部在上面一点
            this.transform.rotation = rotation;
        }
        else   //第三人称时向下偏移一点，免得挡住屏幕
        {
            this.transform.position = new Vector3(position.x, position.y+2, position.z);
            this.transform.rotation = rotation;
        }
        

        target.transform.rotation = Quaternion.Euler(0, y, 0);
    }
}
